import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { RightOutline, SearchOutline, LoopOutline } from 'antd-mobile-icons';
import { Popup, Radio, Toast, Button } from 'antd-mobile';
import axios from 'axios';
import FormData from 'form-data';
import { getUserId, getSchoolId } from '../utils/auth';
import { http, host, port } from '../utils/host'
import FileUpload from '../may/LargeFileUpload'
// 定义话题接口
interface Topic {
  _id: string;
  title: string;
  // 其他话题相关字段
}

// 定义文件项接口
interface FileItem {
  id: string;
  file: File;
  url: string;
  type: 'image' | 'video';
}

const Publish: React.FC = () => {
  const navigate = useNavigate();
  const [title, setTitle] = useState<string>('');
  const [topics, setTopics] = useState<Topic[]>([]);
  const [showTopicPopup, setShowTopicPopup] = useState<boolean>(false);
  const [selectedTopic, setSelectedTopic] = useState<string | null>(null);
  const [selectedTopicTitle, setSelectedTopicTitle] = useState<string>('');
  const [files, setFiles] = useState<FileItem[]>([]);
  const [uploading, setUploading] = useState<boolean>(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [aiProcessing, setAiProcessing] = useState<boolean>(false);

  // AI一键补全功能（基于DeepSeek API优化）
  const handleAiComplete = async () => {
    if (files.length === 0) {
      Toast.show({ content: '请先上传图片', type: 'fail', position: 'center' });
      return;
    }

    if (aiProcessing) {
      return;
    }

    setAiProcessing(true);
    try {
      // 准备FormData
      const formData = new FormData();
      // 只发送第一张图片用于AI分析
      formData.append('file', files[0].file);

      // 调用后端AI接口
      const response = await axios.post(`${http}${host}${port}/api/ai/complete`, {
        imageUrl: files[0].url,
        prompt: '为这张图片生成一个吸引人的标题和合适的话题',
        maxTokens: 100,
        temperature: 0.7
      });

      // 更新标题和话题
      if (response.data.title) {
        setTitle(response.data.title);
      }

      if (response.data.topic) {
        // 查找匹配的话题
        const matchedTopic = topics.find(topic => topic.title === response.data.topic);
        if (matchedTopic) {
          setSelectedTopic(matchedTopic._id);
          setSelectedTopicTitle(matchedTopic.title);
        } else {
          // 如果没有匹配的话题，显示建议的话题
          Toast.show({ content: `建议话题: ${response.data.topic}`, type: 'info', position: 'center' });
        }
      }

      Toast.show({ content: 'AI补全成功', type: 'success', position: 'center' });
    } catch (error) {
      console.error('AI补全失败:', error);
      const errorMessage = error.response?.data?.error || 'AI补全失败，请重试';
      Toast.show({ content: errorMessage, type: 'fail', position: 'center' });
    } finally {
      setAiProcessing(false);
    }
  }

  useEffect(() => {
    const fetchTopics = async (): Promise<void> => {
      try {
        const response = await axios.get(`${http}${host}${port}/hua/detail`);
        setTopics(response.data);
      } catch (error) {
        console.error('获取话题失败:', error);
      }
    };

    fetchTopics();
  }, []);

  const handleCancel = (): void => {
    navigate(-1);
  };

  const handlePublish = async (fileUrls: string[] = []): Promise<void> => {
    try {
      const userId = getUserId();
      const schoolId = getSchoolId();

      if (!userId) {
        Toast.show({ content: '请先登录', type: 'fail', position: 'center' });
        return;
      }

      if (!schoolId) {
        Toast.show({ content: '未获取到学校信息，请重新登录', type: 'fail', position: 'center' });
        return;
      }

      if (!selectedTopic || !title) {
        Toast.show({ content: '请选择话题和填写标题', type: 'fail', position: 'center' });
        return;
      }
      const localFileUrls = JSON.parse(localStorage.getItem('fileUrls') || '[]');
      const response = await axios.post(`${http}${host}${port}/dongtai/publish`, {
        userId,
        huaId: selectedTopic,
        schoolId,
        title,
        media: localFileUrls// 上传文件后返回的url数组
      });

      Toast.show({ content: '发布成功', type: 'success', position: 'center' });
      navigate(-1);
    } catch (error) {
      console.error('发布失败:', error);
      Toast.show({ content: '发布失败，请重试', type: 'fail', position: 'center' });
    }
  };

  const handleTopicSelect = (topic: Topic): void => {
    setSelectedTopic(topic._id);
    setSelectedTopicTitle(topic.title);
    setShowTopicPopup(false);
  };

  const handleTopicConfirm = (): void => {
    setShowTopicPopup(false);
  };

  // 文件选择处理
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    const selectedFiles = event.target.files;
    if (selectedFiles.length > 0) {
      const newFiles = Array.from(selectedFiles).map(file => ({
        id: Date.now() + Math.random().toString(36).substring(2, 10),
        file,
        url: URL.createObjectURL(file),
        type: file.type.startsWith('image/') ? 'image' : 'video'
      }));

      // 限制最多9个文件
      if (files.length + newFiles.length > 9) {
        Toast.show({ content: '最多只能上传9个文件', type: 'info', position: 'center' });
        return;
      }

      setFiles([...files, ...newFiles]);
    }
  };

  // 移除文件
  const handleRemoveFile = (id: string): void => {
    setFiles(files.filter(file => file.id !== id));
  };

  // 上传文件
  const uploadFiles = async (): Promise<void> => {
    setUploading(true);
    setUploadProgress(0);

    try {
      const formData = new FormData();
      files.forEach(file => {
        formData.append('files', file.file);
      });

      // 移除手动设置的Content-Type，让浏览器自动处理（包括boundary）
      const response = await axios.post(`${http}${host}${port}/upload/file`, formData, {
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setUploadProgress(percentCompleted);
        }
      });

      setUploading(false);
      Toast.show({ content: '文件上传成功', type: 'success', position: 'center' });
      const localFileUrls = JSON.parse(localStorage.getItem('fileUrls') || '[]');
      handlePublish(localFileUrls);
    } catch (error) {
      console.error('文件上传失败:', error);
      setUploading(false);
      // 显示后端返回的具体错误信息
      const errorMessage = error.response?.data?.error || '文件上传失败，请重试';
      Toast.show({ content: errorMessage, type: 'fail', position: 'center' });
      // 建议检查后端uploads目录
      console.log('提示: 请确保后端promo-backend目录下存在uploads目录，并且服务器有写入权限。');
    }
  };

  // 发布前先上传文件
  const handlePublishWithUpload = (): void => {
    if (files.length > 0) {
      uploadFiles();
    } else {
      handlePublish([]);
    }
  };

  return (
    <div style={styles.container}>
      {/* 顶部导航栏 */}
      <div style={styles.header}>
        <span style={styles.cancelButton} onClick={handleCancel}>取消</span>
        <h1 style={styles.title}>发动态</h1>
        <span style={{ ...styles.publishButton, opacity: uploading ? 0.7 : 1, cursor: uploading ? 'not-allowed' : 'pointer' }} onClick={uploading ? () => { } : handlePublishWithUpload}>{uploading ? '上传中...' : '发布'}</span>
      </div>

      {/* 内容区域 */}
      <div style={styles.content}>
        {/* 标题输入框和AI补全按钮 */}
        <div style={styles.titleContainer}>
          <input
            style={styles.input}
            placeholder="输入标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <Button
            style={styles.aiButton}
            onClick={handleAiComplete}
            loading={aiProcessing}
            disabled={aiProcessing || files.length === 0}
          >
            {aiProcessing ? <LoopOutline size="small" /> : <SearchOutline size="small" />}
            <span style={styles.aiButtonText}>AI一键补全</span>
          </Button>
        </div>

        {/* 图片上传区域 */}
        <div style={styles.imageUpload}>
          {/* <input
            type="file"
            multiple
            accept="image/*,video/*"
            style={{ display: 'none' }}
            id="fileUpload"
            onChange={handleFileChange}
          />
          <label htmlFor="fileUpload" style={styles.uploadPlaceholder}>
            <span style={styles.plusIcon}>+</span>
            <span style={styles.uploadText}>点击上传图片或视频</span>
          </label> */}
          <FileUpload></FileUpload>
          {/* 文件预览区域 */}
          {files.length > 0 && (
            <div style={styles.previewContainer}>
              {files.map(file => (
                <div key={file.id} style={styles.previewItem}>
                  {file.type === 'image' ? (
                    <img
                      src={file.url}
                      alt="预览图"
                      style={styles.previewImage}
                    />
                  ) : (
                    <video
                      src={file.url}
                      style={styles.previewVideo}
                      controls
                    />
                  )}
                  <button
                    style={styles.removeButton}
                    onClick={() => handleRemoveFile(file.id)}
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
          )}

          {/* 上传进度条 */}
          {uploading && (
            <div style={styles.progressContainer}>
              <div
                style={{ ...styles.progressBar, width: `${uploadProgress}%` }}
              />
              <span style={styles.progressText}>{uploadProgress}%</span>
            </div>
          )}
        </div>

        {/* 添加话题区域 */}
        <div style={styles.topicSection} onClick={() => setShowTopicPopup(true)}>
          <span style={{ ...styles.topicText, ...(selectedTopicTitle ? { color: '#333333' } : {}) }}>{selectedTopicTitle || '添加话题'}</span>
          <RightOutline />
        </div>
      </div>

      {/* 话题选择Popup */}
      <Popup
        visible={showTopicPopup}
        onClose={() => setShowTopicPopup(false)}
        position="bottom"
        bodyStyle={{ height: '60%', overflow: 'auto', padding: '16px' }}
        closeOnMaskClick={true}
      >
        <div style={styles.popupHeader}>
          <h2 style={styles.popupTitle}>选择要发布的话题</h2>
        </div>
        <div style={styles.topicList}>
          {topics.map(topic => (
            <div
              key={topic._id}
              style={{ ...styles.topicItem, ...(selectedTopic === topic._id ? styles.selectedTopic : {}) }}
              onClick={() => handleTopicSelect(topic)}
            >
              <Radio checked={selectedTopic === topic._id} />
              <span style={styles.topicName}>{topic.title}</span>
            </div>
          ))}
        </div>
      </Popup>
    </div>
  );
};

const styles = {
  container: {
    width: '100%',
    height: '100vh',
    backgroundColor: '#FFFFFF',
  },
  titleContainer: {
    display: 'flex',
    gap: '10px',
    marginBottom: '16px',
  },
  aiButton: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '6px',
    backgroundColor: '#4A90E2',
    color: 'white',
    border: 'none',
    borderRadius: '8px',
    padding: '0 16px',
    cursor: 'pointer',
    height: '44px',
    fontSize: '14px',
    fontWeight: '500',
  },
  aiButtonText: {
    whiteSpace: 'nowrap',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderBottom: '1px solid #F5F5F5',
  },
  cancelButton: {
    fontSize: '16px',
    color: '#333333',
  },
  title: {
    fontSize: '18px',
    fontWeight: 'bold',
    margin: 0,
  },
  publishButton: {
    fontSize: '16px',
    color: '#FFFFFF',
    backgroundColor: '#FF6B6B',
    padding: '8px 16px',
    borderRadius: '20px',
  },
  content: {
    padding: '16px',
    maxWidth: '600px',
    margin: '0 auto',
    width: '100%',
    boxSizing: 'border-box',
  },
  input: {
    width: '100%',
    height: '44px',
    padding: '12px',
    border: '1px solid #EEEEEE',
    borderRadius: '8px',
    fontSize: '16px',
    marginBottom: '16px',
    boxSizing: 'border-box',
  },
  imageUpload: {
    marginBottom: '16px',
  },
  uploadPlaceholder: {
    width: '100%',
    height: '120px',
    border: '1px dashed #DDDDDD',
    borderRadius: '8px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    transition: 'all 0.3s ease',
  },
  'uploadPlaceholder:hover': {
    borderColor: '#FF6B6B',
    backgroundColor: '#FFF0F0',
  },
  plusIcon: {
    fontSize: '28px',
    color: '#999999',
    marginBottom: '8px',
  },
  uploadText: {
    fontSize: '14px',
    color: '#999999',
  },
  previewContainer: {
    display: 'flex',
    flexWrap: 'wrap',
    gap: '12px',
    marginTop: '16px',
  },
  previewItem: {
    position: 'relative',
    width: '90px',
    height: '90px',
    borderRadius: '8px',
    overflow: 'hidden',
  },
  previewImage: {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
  },
  previewVideo: {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
  },
  removeButton: {
    position: 'absolute',
    top: '4px',
    right: '4px',
    width: '24px',
    height: '24px',
    borderRadius: '50%',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    color: 'white',
    border: 'none',
    fontSize: '16px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
  },
  progressContainer: {
    width: '100%',
    height: '8px',
    backgroundColor: '#F5F5F5',
    borderRadius: '4px',
    marginTop: '16px',
    overflow: 'hidden',
    position: 'relative',
  },
  progressBar: {
    height: '100%',
    backgroundColor: '#FF6B6B',
    transition: 'width 0.3s ease',
  },
  progressText: {
    position: 'absolute',
    right: '8px',
    top: '-24px',
    fontSize: '12px',
    color: '#666666',
  },
  topicSection: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '12px',
    border: '1px solid #EEEEEE',
    borderRadius: '8px',
    fontSize: '16px',
  },
  topicText: {
    color: '#666666',
  },
  popupHeader: {
    paddingBottom: '16px',
    borderBottom: '1px solid #F5F5F5',
    marginBottom: '16px',
  },
  popupTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    margin: 0,
    textAlign: 'center',
  },
  topicList: {
    marginBottom: '24px',
  },
  topicItem: {
    display: 'flex',
    alignItems: 'center',
    padding: '12px 0',
    borderBottom: '1px solid #F5F5F5',
  },
  topicName: {
    marginLeft: '12px',
    fontSize: '16px',
  },
  popupFooter: {
    paddingTop: '16px',
    borderTop: '1px solid #F5F5F5',
  },
  confirmButton: {
    width: '100%',
    height: '44px',
    backgroundColor: '#FF6B6B',
    color: '#FFFFFF',
    border: 'none',
    borderRadius: '8px',
    fontSize: '16px',
    cursor: 'pointer',
  },
  selectedTopic: {
    backgroundColor: '#FFF0F0',
  },
};

export default Publish;